<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\ProvinceCategory;
use App\Models\StoreInfo;
use App\Models\UserAssist;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class DealerController extends Controller
{

    private $storeInfo;

    public function create(Request $request)
    {
        checkAuthority();
        $page = [
            'page_name' => 'dealer',
            'title' => ts('ADDDEALER'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEDEALERS'),
                    'url' => '/admin/dealer'
                ]
            ],
        ];
        $data = new Admin();
        $data->unique_id = makeUniqueId();

        $model = Admin::where('user_type', 2)->where('status', 1);
        if (session('admin.user_type') == 2) {
            $model = $model->where('id', session('admin.id'));
        }
        $distributions = $model->orderBy('unique_id')->get(['id', 'abbr']);
        return view('admin.dealer.create', [
            'data'=>$data,
            'page' => $page,
            'distributions' => $distributions,
            'user_type' => session('admin.user_type'),
        ]);
    }

    public function edit(Request $request, $id)
    {
        checkAuthority();
        $page = [
            'page_name' => 'dealer',
            'title' => ts('editDEALER'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEDEALERS'),
                    'url' => '/admin/dealer'
                ]
            ],
        ];
        $data = Admin::findOrFail($id);
        if ($data->user_type != 3) {
            abort(404);
        }
        $dealer = DB::table('dealer')->where('user_id', $id)->first();

        $user = DB::table('users')->select('category_code', 'category_name')->where('id', $id)->first(); // 用户信息

        if (!empty($dealer) && !empty($dealer->system_info)) {
            $system_info = json_decode($dealer->system_info, true);
            if (!empty($system_info)) {
                $dealer->system_info = $system_info;
            } else {
                $dealer->system_info = [];
            }
        }
        if (!empty($dealer) && !empty($dealer->cert_person)) {
            $cert_person = json_decode($dealer->cert_person, true);
            if (!empty($cert_person)) {
                $dealer->cert_person = $cert_person;
            } else {
                $dealer->cert_person = [];
            }
        }
        if (!empty($dealer) && !empty($dealer->store_pictures)) {
            $dealer->store_pictures = explode(',', $dealer->store_pictures);
        }
        if (!empty($dealer) && !empty($dealer->agreement_pictures)) {
            $dealer->agreement_pictures = explode(',', $dealer->agreement_pictures);
        }
        if (!empty($dealer)) {
            $storeInfo = DB::table('store_info')->where('user_id', $id)->first();
        }

        $model = Admin::where('user_type', 2)->where('status', 1);
        if (session('admin.user_type') == 2) {
            $model = $model->where('id', session('admin.id'));
        }
        $distributions = $model->orderBy('unique_id')->get(['id', 'abbr']);
        if (empty($storeInfo->new_store_code)) {
            $province = DB::table('province_master')->where('id', $data->province_id)->first();
            $sql = 'SELECT COUNT(1) AS cnt FROM store_info WHERE new_store_code LIKE "' . $province->abbreviation . '%"';
            $result = DB::select($sql);
            $new_store_code = $province->abbreviation . str_pad($result[0]->cnt + 1, 3, 0, STR_PAD_LEFT);
        } else {
            $new_store_code = $storeInfo->new_store_code;
        }

        return view('admin.dealer.edit', [
            'data'=>$data,
            'dealer' => $dealer,
            'page' => $page,
            'user'          => $user,
            'distributions' => $distributions,
            'store_info'    => $storeInfo ?? [],
            'new_store_code' => $new_store_code,
            'user_type'     => session('admin.user_type')
        ]);
    }


    /*
     * 存储*/
    public function store(Request $request)
    {
        checkAuthority();
        $page = [
            'page_name' => 'dealer',
            'title' => ts('DEALER'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEDEALERS'),
                    'url' => '/admin/dealer'
                ]
            ],
        ];
        /*$unique_id = trim($request->input('unique_id'));
        $pm = '/^CN[0-9]{4,7}$/';
        $unique_id = str_replace(' ', '', $unique_id);
        $unique_id = strtoupper($unique_id);
        if (!preg_match($pm, $unique_id)) {
            return redirect()->back()->withInput()->with('trash', ['type'=>'error', 'content'=>'账号不符合规则！账号规则为CN+（4-7）位数字组成！']);
        }*/
        $abbr = trim($request->input('abbr'));
        if (empty($abbr)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '店面名称不能为空!'
            ]);
        }

        $mod = new Admin();
        $mod->unique_id = makeUniqueId();
        $mod->user_type = 3;
        $mod->company_name = trim($request->input('company_name'));
        $mod->abbr = trim($request->input('abbr'));
        $mod->first_name = trim($request->input('first_name'));
        $mod->email_address = trim($request->input('email_address'));
        $mod->address = trim($request->input('address'));
        $mod->phone_number = trim($request->input('phone_number'));
        $mod->cell_phone = trim($request->input('cell_phone'));
        $mod->wechat_id = trim($request->input('wechat_id'));
        $mod->region_id = (int) $request->input('region_id');
        $mod->province_id = (int) $request->input('province_id');
        $mod->city = (int) $request->input('city');
        $mod->note = trim($request->input('note'));
        $mod->creator_id = (int) $request->input('creator_id');
        $mod->last_name = '';
        $mod->username = '';
        $mod->zip = 0;
        $mod->date_signedup = date('Y-m-d H:i:s');
        $mod->additional_comment = '';
        $mod->province = ts('province_master'.(int) $request->input('province_id'));
        $mod->status = (int) $request->input('status');
        $mod->zsdj = (int) $request->input('zsdj');
        $mod->jsdj = (int) $request->input('jsdj');
        $mod->pay_account = trim($request->input('pay_account'));
        $mod->language_id = (int) $request->input('language_id');
        $extension = trim($request->input('extension'));
        $mod->extension = $extension;
        $mod->check_status = session('admin.user_type') == 1 ? 1 : 0;
        $mod->created_by = session('admin.id');
        $mod->password = Str::random(64);
        $mod->company_name = $mod->company_name ?: $mod->abbr;
        $mod->mdtype = (int) $request->input('mdtype');

        $provinceCategory= ProvinceCategory::where('user_type',$mod->user_type)->where('province_id',$mod->province_id)->first();
        $mod->category_code = $provinceCategory->category_code ?? '';
        $mod->category_name = $provinceCategory->category_name ?? '';
        if($mod->user_type == 3 && in_array($mod->city,[237,4])){
            $mod->category_code = '0212';
            $mod->category_name = '直营参股店';
        }

        $saveResult = $mod->save();
        $alogs = alogs('经销商', '添加', $mod->id, $mod, null);
        if ($saveResult) {
            $userId = $mod->id;
            $storage_images = $request->input('storage_images');
            $images = $request->input('images');
            $system_user = $request->input('system_user');
            $system_name = $request->input('system_name');
            $system_phone = $request->input('system_phone');
            $cert_person = $request->input('cert_person');
            $cert_person_mobile = $request->input('cert_person_mobile');
            $cert_person_level = $request->input('cert_person_level');
            $cert_picture = $request->input('cert_picture');
            $cert_price = $request->input('cert_fee');
            $cert_date = $request->input('cert_date');
            $insertData = [];
            if (empty($request->input('task_value'))) {
                if (in_array($mod->mdtype, [1, 3, 4])) {
                    $insertData['task_value'] = 15;
                }
                if ($mod->mdtype == 2) {
                    $insertData['task_value'] = 4;
                }
            }

            if (!empty($request->input('task_value'))) {
                $insertData['task_value'] = (int)$request->input('task_value');
            }
            if (!empty($request->input('win_task_value'))) {
                $insertData['win_task_value'] = (int)$request->input('win_task_value');
            }
            if (!empty($request->input('cert_status'))) {
                $insertData['cert_status'] = (int)$request->input('cert_status');
            }

            if (!empty($storage_images) && is_array($storage_images)) {
                $insertData['store_pictures'] = implode(',', $storage_images);
            }
            if (!empty($images) && is_array($images)) {
                $insertData['agreement_pictures'] = implode(',', $images);
            }

            if (!empty($cert_picture)) {
                $insertData['cert_picture'] = $cert_picture;
            }
            if (!empty($cert_date)) {
                $insertData['cert_date'] = $cert_date;
            }
            if (!empty($cert_price)) {
                $insertData['cert_price'] = $cert_price;
            }
            if (!empty($cert_person)) {
                $certPersonData = [];
                foreach ($cert_person as $key => $value) {
                    $certPersonData[] = [
                        'name'  => $value,
                        'level' => $cert_person_level[$key] ?? '',
                        'mobile'    => $cert_person_mobile[$key] ?? ''
                    ];
                }
                if (!empty($certPersonData)) {
                    $insertData['cert_person'] = json_encode($certPersonData);
                }
            }

            if (!empty($system_name) && !empty($system_user) && !empty($system_phone)) {
                $jsonData = [];
                foreach ($system_name as $key => $item) {
                    $jsonData[] = [
                        'system_user'   => $system_user[$key],
                        'system_name'   => $item,
                        'system_phone'  => $system_phone[$key],
                    ];
                }
                if (!empty($jsonData)) {
                    $insertData['system_info'] = json_encode($jsonData);
                }
            }

            if (!empty($insertData)) {
                $insertData['user_id'] = $userId;
                DB::table('dealer')->insert($insertData);
            }

            try {
                $this->saveStoreInfo($request->input(), $userId);
            } catch (\Exception $exception) {
                return response()->json([
                    'code'  => 10000,
                    'msg'   => $exception->getMessage()
                ]);

            }
        }


        return response()->json([
            'code'  => 0,
            'url'   => '/admin/dealer/'.$mod->id,
            'msg'   => ''
        ]);

        return redirect('/admin/dealer/'.$mod->id)->with('trash', ts('DEALERADDSUCCESS'));
    }

    public function saveStoreInfo(array $input, int $userId)
    {
        $user = DB::table('store_info')->where('user_id', $userId)->first();
        if (!empty($user)) {
            return $this->updateStoreInfo($userId, $input);
        }

        $this->storeInfo = new StoreInfo();
        $this->storeInfo->user_id = $userId;
        $this->storeInfo->start_date = $input['startdate'] ?? '';
        $this->storeInfo->end_date = $input['enddate'] ?? '';
        $this->storeInfo->open_time = $input['start_time'] ?? '';
        $this->storeInfo->close_time = $input['end_time'] ?? '';
        $this->storeInfo->store_code = $input['store_code'] ?? '';
        $this->storeInfo->video_url = $input['video_url'] ?? '';
        $this->storeInfo->is_advanced = $input['is_advanced'] ?? 0;
        $this->storeInfo->front_show = $input['front_show'] ?? 1;
        $this->storeInfo->detail = $input['content'] ?? '';
        $this->storeInfo->city_id = $input['store_city'] ?? 0;
        if (!empty($input['honor'])) {
            $this->storeInfo->honor = $input['honor'];
        }
        if (!empty($input['new_store_code'])) {
            $this->storeInfo->new_store_code = $input['new_store_code'];
            $codeResult = DB::table('store_info')->where('new_store_code', $input['new_store_code'])->first();
            if (!empty($codeResult) && !empty($codeResult->id)) {
                $input['new_store_code'] = '';
            }
        }

        if (empty($input['new_store_code'])) {
            $province = DB::table('province_master')->where('id', $input['province_id'])->first();
            $sql = 'SELECT COUNT(1) AS cnt FROM store_info WHERE new_store_code LIKE "' . $province->abbreviation . '%"';
            $result = DB::select($sql);
            $this->storeInfo->new_store_code = $province->abbreviation . str_pad($result[0]->cnt + 1, 3, 0, STR_PAD_LEFT);
        }
        if (!empty($input['order_address'])) {
            $this->storeInfo->order_address = $input['order_address'];
        }
        if (!empty($input['order_name'])) {
            $this->storeInfo->order_name = $input['order_name'];
        }
        if (!empty($input['order_mobile'])) {
            $this->storeInfo->order_mobile = $input['order_mobile'];
        }
        if (!empty($input['qrcode_images'])) {
            $this->storeInfo->qrcode_url = implode(',', $input['qrcode_images']);
        }
        if (!empty($input['picture_url'])) {
            $this->storeInfo->picture_url = implode(',', $input['picture_url']);
        }
        $this->storeInfo->save();
        $id = $this->storeInfo->id;
        if (empty($id)) {
            throw new \Exception('添加失败');
        }

        $insertData = [];
        if (!empty($features_image)) {
            foreach ($input['features_images'] as $key => $features_image) {
                $insertData[] = [
                    'store_id'  => $id,
                    'picture_url'   => $features_image,
                    'detail'        => $input['detail_desc'] && !empty($input['detail_desc'][$key]) ? $input['detail_desc'][$key] : '',
                ];
            }
            if (!empty($insertData)) {
                DB::table('store_features')->insert($insertData);
            }
        }
    }

    public function updateStoreInfo(int $id, array $input)
    {
        $store = DB::table('store_info')->where('user_id', $id)->first();
        $updateData['start_date'] = $input['startdate'] ?? '';
        $updateData['end_date'] = $input['enddate'] ?? '';
        $updateData['open_time'] = $input['start_time'] ?? '';
        $updateData['close_time'] = $input['end_time'] ?? '';
        $updateData['video_url'] = $input['video_url'] ?? '';
        if(session()->get('admin.user_type')==1){
            $updateData['is_advanced'] = $input['is_advanced'] ?? '';
            $updateData['front_show'] = $input['front_show'] ?? '';
        }

        $updateData['store_code'] = $input['store_code'] ?? '';
        $updateData['detail'] = $input['content'] ?? '';
        $updateData['persons'] = $input['persons'] ?? '';
        $updateData['city_id'] = $input['store_city'] ?? '';
        $updateData['user_id'] = $id;
        if (!empty($input['new_store_code'])) {
            $updateData['new_store_code'] = $input['new_store_code'];
            $codeResult = DB::table('store_info')->where('new_store_code', $input['new_store_code'])->first();
            if (!empty($codeResult) && !empty($codeResult->id) && $codeResult->user_id != $id) {
                $input['new_store_code'] = '';
            }
        }
        if (empty($input['new_store_code'])) {
            $province = DB::table('province_master')->where('id', $input['province_id'])->first();
            $sql = 'SELECT COUNT(1) AS cnt FROM store_info WHERE new_store_code LIKE "' . $province->abbreviation . '%"';
            $result = DB::select($sql);
            $updateData['new_store_code'] = $province->abbreviation . str_pad($result[0]->cnt + 1, 3, 0, STR_PAD_LEFT);
        }
        if (!empty($input['order_address'])) {
            $updateData['order_address'] = $input['order_address'];
        }
        if (!empty($input['order_name'])) {
            $updateData['order_name'] = $input['order_name'];
        }
        if (!empty($input['order_mobile'])) {
            $updateData['order_mobile'] = $input['order_mobile'];
        }

        if (!empty($input['honor'])) {
            $updateData['honor'] = $input['honor'];
        }
        if (!empty($input['images'])) {
            $updateData['picture_url'] = implode(',', $input['images']);
        }
        if (!empty($input['qrcode_images'])) {
            $updateData['qrcode_url'] = implode(',', $input['qrcode_images']);
        }
        $updateData['is_delete'] = 0;
        if (empty($store)) {
            $store_id = DB::table('store_info')->insertGetId($updateData);
        } else {
            DB::table('store_info')->where('user_id', $id)->update($updateData);
            $store_id = $store->id;
        }
        if (!empty($input['features_images'])) {
            DB::table('store_features')->where('store_id', $store_id)->delete();
            $insertData = [];
            foreach ($input['features_images'] as $key => $features_image) {
                $insertData[] = [
                    'store_id'  => $store_id,
                    'picture_url'   => $features_image,
                    'detail'        => $input['detail_desc'] && !empty($input['detail_desc'][$key]) ? $input['detail_desc'][$key] : '',
                    'type'          => 1,
                ];
            }
            if (!empty($insertData)) {
                DB::table('store_features')->insert($insertData);
            }
        }

        if (!empty($input['picture_images'])) {
            $insertData = [];
            foreach ($input['picture_images'] as $key => $features_image) {
                $insertData[] = [
                    'store_id'  => $store_id,
                    'picture_url'   => $features_image,
                    'detail'        => $input['picture_desc'] && !empty($input['picture_desc'][$key]) ? $input['picture_desc'][$key] : '',
                    'type'          => 2,
                ];
            }
            if (!empty($insertData)) {
                DB::table('store_features')->insert($insertData);
            }
        }
    }

    public function update(Request $request, $id)
    {
        $page = [
            'page_name' => 'dealer',
            'title' => ts('DEALER')
        ];
        $mod = Admin::findOrFail($id);
        if ($mod->user_type != 3) {
            return response()->json([
                'code'  => 10000,
                'msg'   => '数据不存在! ',
            ]);
        }

        $abbr = trim($request->input('abbr'));
        if (empty($abbr)) {
            return response()->json([
                'code'  => 10000,
                'msg'   => '店面名称不能为空! ',
            ]);
        }

        $differ = modelDiff($mod, $request->input(), [
            'company_name',
            'abbr',
            'first_name',
            'email_address',
            'address',
            'phone_number',
            'cell_phone',
            'wechat_id',
            'region_id',
            'province_id',
            'city',
            'note',
            'extension',
            'status',
            'mdtype',
            'jsdj',
            'jshudj',
            'jsdj_number',
            'jshudj_number',
            'zsdj',
            'creator_id'
        ]);
        if ($differ) {

            $model = new UserAssist();
            $model->user_id = $mod->id;
            $model->status = 9; // 数组
            $model->note = json_encode($differ);
            $model->created_by = session('admin.id');
            $model->save();
        }

        $alogs = alogs('经销商', '修改', $mod->id, null, $mod);
        $mod->company_name = trim($request->input('company_name'));
        $mod->abbr = trim($request->input('abbr'));
        $mod->first_name = trim($request->input('first_name'));
        $mod->email_address = trim($request->input('email_address'));
        $mod->address = trim($request->input('address'));
        $mod->phone_number = trim($request->input('phone_number'));
        $mod->cell_phone = trim($request->input('cell_phone'));
        $mod->wechat_id = trim($request->input('wechat_id'));
        $mod->region_id = (int) $request->input('region_id');
        $mod->province_id = (int) $request->input('province_id');
        $mod->city = (int) $request->input('city');
        $mod->note = trim($request->input('note'));
        $mod->creator_id = (int) $request->input('creator_id');
        $mod->zsdj = (int) $request->input('zsdj');
        $mod->jsdj = (int) $request->input('jsdj');
        $mod->jshudj = (int) $request->input('jshudj');
        $mod->jsdj_number = (int) $request->input('jsdj_number');
        $mod->jshudj_number = (int) $request->input('jshudj_number');
        $mod->pay_account = trim($request->input('pay_account'));
        $extension = trim($request->input('extension'));
        $mod->extension = $extension;

        $mod->updated_by = session('admin.id');

        $mod->company_name = $mod->company_name ?: $mod->abbr;
        $mod->mdtype = (int) $request->input('mdtype');

        $status = (int) $request->input('status');

        if (session('admin.user_type') == 2) {
            $mod->check_status = 0;
        }

        $mod->status = $status;
        $saveResult = $mod->save();
        if ($saveResult) {
            $userId = $mod->id;
            $storage_images = $request->input('storage_images');
            $images = $request->input('images');
            $system_user = $request->input('system_user');
            $system_name = $request->input('system_name');
            $system_phone = $request->input('system_phone');
            $cert_person = $request->input('cert_person');
            $cert_person_mobile = $request->input('cert_person_mobile');
            $cert_person_level = $request->input('cert_person_level');
            $cert_picture = $request->input('cert_picture');
            $cert_price = $request->input('cert_fee');
            $cert_date = $request->input('cert_date');
            $insertData = [];
            if (empty($request->input('task_value'))) {
                if (in_array($mod->mdtype, [1, 3, 4])) {
                    $insertData['task_value'] = 15;
                }
                if ($mod->mdtype == 2) {
                    $insertData['task_value'] = 4;
                }
            }

            if (!empty($request->input('task_value'))) {
                $insertData['task_value'] = (int)$request->input('task_value');
            }
            if (!empty($request->input('win_task_value'))) {
                $insertData['win_task_value'] = (int)$request->input('win_task_value');
            }
            if (!empty($cert_picture)) {
                $insertData['cert_picture'] = $cert_picture;
            }
            if (!empty($cert_date)) {
                $insertData['cert_date'] = $cert_date;
            }
            if (!empty($cert_price)) {
                $insertData['cert_price'] = $cert_price;
            }
            if (!empty($request->input('cert_status'))) {
                $insertData['cert_status'] = (int)$request->input('cert_status');
            }

            if (!empty($storage_images) && is_array($storage_images)) {
                $insertData['store_pictures'] = implode(',', $storage_images);
            }
            if (!empty($images) && is_array($images)) {
                $insertData['agreement_pictures'] = implode(',', $images);
            }
            if (!empty($cert_person)) {
                $certPersonData = [];
                foreach ($cert_person as $key => $value) {
                    $certPersonData[] = [
                        'name'  => $value,
                        'level' => $cert_person_level[$key] ?? '',
                        'mobile'    => $cert_person_mobile[$key] ?? ''
                    ];
                }
                if (!empty($certPersonData)) {
                    $insertData['cert_person'] = json_encode($certPersonData);
                }
            }

            if (!empty($system_name) && !empty($system_user) && !empty($system_phone)) {
                $jsonData = [];
                foreach ($system_name as $key => $item) {
                    $jsonData[] = [
                        'system_user'   => $system_user[$key],
                        'system_name'   => $item,
                        'system_phone'  => $system_phone[$key],
                    ];
                }
                if (!empty($jsonData)) {
                    $insertData['system_info'] = json_encode($jsonData);
                }
            }

            if (!empty($insertData)) {
                $insertData['user_id'] = $id;
                $dealer = DB::table('dealer')->where('user_id', $id)->first();
                if ($dealer) {
                    DB::table('dealer')->where('id', $dealer->id)->update($insertData);
                } else {
                    DB::table('dealer')->insert($insertData);
                }
            }

            try {
                $this->saveStoreInfo($request->input(), $id);
            } catch (\Exception $exception) {
                return response()->json([
                    'code'  => 10000,
                    'msg'   => $exception->getMessage(),
                ]);
            }
        }

        $alogs->new = $mod;
        $alogs->save();

        return response()->json([
            'code'  => 0,
            'url'   => '/admin/dealer/'.$mod->id
        ]);
        return redirect('/admin/dealer/'.$mod->id)->with('trash', ts('DEALERUPDATESUCCESS'));
    }

    /*
     * 经销商同步*/
    public function import(Request $request)
    {
        checkAuthority();
        $page = [
            'page_name' => 'distributor',
            'title' => ts('tongbu'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEdealer'),
                    'url' => '/admin/dealer'
                ]
            ],
        ];
        return view('admin.dealer.import', [
            'page' => $page,
        ]);
    }


    /*
     * 经销商同步操作*/
    public function handle_import(Request $request)
    {
        checkAuthority();
        $admin_id = session('admin.id');
        $file = $request->file('file');
        if (empty($file)) {
            return back()->withInput()->with('trash', [ 'content' => '文件不能为空！', 'type' => 'error']);
        }
        $ext = $file->getClientOriginalExtension();
        $allow_type = [
            'csv','xls','xlsx'
        ];
        if (!in_array($ext, $allow_type)) {
            return back()->with('trash', [ 'msg' => '不支持的文件类型！', 'type' => 'error']);
        }
        $filename = Str::random(16) . '.xlsx';
        $path = $this->getFileStorePath(2);
        $bool = $file->storeAs($path['path'], $filename, 'storage');
        $full_file_name = $path['path'].$filename;
        $mod = new FileUpload();
        $mod->type = 2;
        $mod->name = '经销商同步';
        $mod->user_id = $admin_id;
        $mod->file = $full_file_name;
        $mod->save();
        $pfile = $path['base'] . $filename;
        if (file_exists($pfile)) {
            $spreadsheet = IOFactory::load($file);
            $sheet = $spreadsheet->getActiveSheet();
            $row_no = 1;
            $n = 1;
            $data = [];
            while ($n){
                $item = [];
                $n = strtoupper(trim($sheet->getCell('A'.$row_no)->getValue()));
                if ($n) {
                    if ($n != 'ID') {
                        foreach (range('A', 'Q') as $v) {
                            $item[$v] = trim($sheet->getCell($v.$row_no)->getValue());
                        }
                        $data[] = $item;
                    }
                }
                $row_no++;
            }
            $uun = DB::table('users_union')->get();
            $uuids = [];
            foreach ($uun as $v) {
                $uuids[$v->union_id] = $v->user_id;
            }
            $upd = ped1($data); // 将数据转化为经销商键数组
            foreach ($upd as $k => $v) {
                $model = new UserSync();
                $model->union_id = $v['id'];
                $model->user_type = 3;
                if (!empty($uuids->$v['id'])) {
                    $model->user_id = $uuids->$v['id'];
                    $cv = ced1($model->user_id, $v); // 检查经销商与传入值是否有修改
                    if (!$cv) {
                        $model->status = 0;
                    } else {
                        $model->status = 2;
                    }
                } else {
                    $model->status = 0;
                }
                $model->datas = json_encode($v);
                $model->save();
            }
        }
        return redirect('/admin/user_sync');
    }
    /*
     * 整理EXCEL数据*/

    /*
     * 数据导出*/
    public function export(Request $request)
    {
        $user_id = session()->get('admin.id');
        $user_type = session()->get('admin.user_type');

        $m = $request->input('m');


        $model = DB::table('users as x')
            ->leftJoin('users as u', 'u.id', 'x.creator_id')
            ->leftJoin('region_master as rm', 'rm.id', 'x.region_id')
            ->leftJoin('province_master as pm', 'pm.id', 'x.province_id')
            ->leftJoin('cities as ct', 'ct.id', 'x.city')
            ->where('x.user_type', 3)
            ->whereNull('x.deleted_at')
            ->select(['x.*', 'u.abbr as sdqy',
                'u.id as sdid',
                'rm.simplified_chiness_value as rm_name',
                'pm.simplified_chiness_value as pm_name',
                'ct.simplified_chiness_value as ct_name'
            ]);
        if ($user_type == 2) {
            $model = $model->where('x.creator_id', $user_id);
        }
        if ($m == 1) {
            $model = $model->where('x.status', 1);
        }
        $model = filterByColumns($model, ['x.abbr','x.first_name','x.phone_number']);

        $mdtype = $request->input('mdtype');
        if ($mdtype !== null) {
            $model = $model->where('x.mdtype', $mdtype);
        }
        $zsdj = $request->input('zsdj');
        if ($zsdj !== null) {
            $model = $model->where('x.zsdj', $zsdj);
        }
        $data = $model->orderBy('x.status')
            ->orderByRaw(DB::raw('FIELD(x.mdtype, 1,3,4,2)'))
            ->orderBy('x.unique_id')
            ->get();
        $uploads = [];
        $fields = [
            'unique_id' => '账号',
            'mdtype_name' => '门店等级/经销商级别',
            'zsdj_name'   => '钻石等级',
            'distributor_name' => '所属省代',
            'abbr' => '店面名称',
            'rm_name' => '区域',
            'pm_name' => '省',
            'ct_name' => '城市',
            'address' => '地址',
            'first_name' => '联系人姓名',
            'ext_phone' => '电话号码',
            'wechat_id' => '微信ID',
            'additional_comment' => '备注',
        ];
        foreach ($data as $k => $v) {
            $v->mdtype_name = ts('mdtype'.$v->mdtype);
            $v->zsdj_name = ts('zsdj' . $v->zsdj);
            $v->distributor_name = $v->sdqy;
            $v->ext_phone = $v->extension . '-' . $v->phone_number;
            $v->wechat_id = (string) $v->wechat_id;
            $item = [];
            foreach ($fields as $f=>$m) {
                $item[] = [
                    'label' => $m,
                    'value' => $v->$f
                ];
            }
            $uploads[] = $item;
        }
        return makeExcel($uploads, '经销商');
    }

    public function updateStatus(Request $request, int $id)
    {
        $result = Admin::where('id', $id)->update(['check_status' => $request->input('status'), 'check_reason' => $request->input('reason') ?: '']);
        return $result;
    }

    public function storeCode(Request $request)
    {
        $provinceId = $request->input('province_id');
        $province = DB::table('province_master')->where('id', $provinceId)->first();
        $sql = 'SELECT COUNT(1) AS cnt FROM store_info WHERE new_store_code LIKE "' . $province->abbreviation . '%"';
        $result = DB::select($sql);
        $new_store_code = $province->abbreviation . str_pad($result[0]->cnt + 1, 3, 0, STR_PAD_LEFT);

        return response()->json([
            'code'  => 0,
            'new_store_code' => $new_store_code
        ]);
    }
}
